package com.hongdee.scm.pushMessage.service.impl;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.NotificationTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.gexin.rp.sdk.template.style.Style0;
import com.hongdee.base.sendMsg.service.ISendMsgService;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.Constant;
import com.hongdee.scm.pushMessage.dao.ITScmPushMsgDao;
import com.hongdee.scm.pushMessage.service.ITScmPushMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TScmPushMsgServiceImpl implements ITScmPushMsgService {

    @Autowired
    private ITScmPushMsgDao itScmPushMsgDao;
    @Autowired
    private ISendMsgService iSendMsgService;

    /**
     * 个推
     * @param saId
     * @param title
     * @param type
     * @throws Exception
     */
    @Override
    public void push(List<Map<String,Object>> saId, String title,String type) throws Exception{

/*        if(saId.size()==0){
            throw new Exception("用户未登录，推送失败！！");
        }*/

        IGtPush push = new IGtPush(Constant.HOST, Constant.APPKEY, Constant.MASTERSECRET);
        TransmissionTemplate template = transmissionTemplate(title);

        ListMessage message = new ListMessage();
        message.setOffline(true);
        // 离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 3600 * 1000);
        message.setData(template);
        // 可选，1为wifi，0为不限制网络环境。根据手机处于的网络情况，决定是否下发
        message.setPushNetWorkType(0);

        List<Target> targetList = new ArrayList<>();
        for(Map<String,Object> sa:saId){
            Target target = new Target();
            target.setAppId(Constant.APPID);
            target.setClientId(TokenUtil.getClientId(sa.get("id").toString()));
            //target.setAlias(Alias);
            targetList.add(target);
        }

        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);

        IPushResult ret = null;
        try {
            ret = push.pushMessageToList(taskId, targetList);
        } catch (RequestException e) {
            e.printStackTrace();
            ret = push.pushMessageToList(taskId, targetList);
        }
        if (ret != null) {
            System.out.println(ret.getResponse().toString());
        } else {
            System.out.println("服务器响应异常");
        }

    }

    /**
     * 应用模板
     * @param title
     * @return
     */
    public static TransmissionTemplate transmissionTemplate(String title){

        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(Constant.APPID);
        template.setAppkey(Constant.APPKEY);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(2);
        template.setTransmissionContent(title);
        // 设置定时展示时间
        // template.setDuration("2015-01-16 11:40:00", "2015-01-16 12:24:00");

       /* Style0 style = new Style0();
        // 设置通知栏标题与内容
        style.setTitle(title);
        style.setText(text);
        // 配置通知栏图标
        style.setLogo("icon.png");
        // 配置通知栏网络图标
        style.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        style.setRing(true);
        style.setVibrate(true);
        style.setClearable(true);
        template.setStyle(style);*/

        return template;
    }

    /**
     * 消息中心
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public List messageCenter(String uid) throws Exception{
        //type:1调拨2出库确认3入库确认
        List dataList = new ArrayList();
        String cid = TokenUtil.getCompanyId(uid);
        String power = "";
        //登录人的权限
        List<Map<String,Object>> list = this.confirmRole(uid);
        for(Map m:list){
            if("确认入库".equals(m.get("source"))&&!power.equals(m.get("source"))){

                StringBuffer sql = new StringBuffer();
                List params = new ArrayList();
                sql.append("select c.update_time,ifnull(count(1),0) as value " +
                        "from (select * from t_scm_car c where c.status = '0' and c.finance_type ='1'  " +
                        "and c.company_id = ?  ORDER BY update_time desc) c group by c.company_id limit 1");
                if(cid!=null&&!cid.equals("")){
                    params.add(cid);
                }
                Map map = this.itScmPushMsgDao.info(sql.toString(),params.toArray());
                int inCar = Integer.parseInt(map.get("value").toString());
                if(inCar>0){
                    Map mm = new HashMap();
                    mm.put("title","待确认入库："+inCar+"辆");
                    mm.put("content","请及时到PC端确认！");
                    mm.put("createTime",map.get("updateTime"));
                    mm.put("type",3);
                    dataList.add(mm);
                }
            }

            if("确认出库".equals(m.get("source"))&&!power.equals(m.get("source"))){

                StringBuffer sql = new StringBuffer();
                List params = new ArrayList();
                sql.append("select c.create_time,ifnull(count(1),0) as value from (" +
                        " select * from t_scm_outwarehouse where out_status = '0' and company_id=?" +
                        " order by create_time desc ) c group by c.company_id limit 1");
                if(cid!=null&&!cid.equals("")){
                    params.add(cid);
                }
                Map map = this.itScmPushMsgDao.info(sql.toString(),params.toArray());
                int outCar = Integer.parseInt(map.get("value").toString());
                if(outCar>0){
                    Map mm = new HashMap();
                    mm.put("title","待确认出库："+outCar+"辆");
                    mm.put("content","请及时到PC端确认！");
                    mm.put("createTime",map.get("createTime"));
                    mm.put("type",2);
                    dataList.add(mm);
                }
            }

            if("调拨审批".equals(m.get("source"))&&!power.equals(m.get("source"))){

                StringBuffer sql = new StringBuffer();
                List params = new ArrayList();
                sql.append("select c.create_time,count(1) as value from ( " +
                        "SELECT p.create_time,p.company_id,tbu.u_name, w1.warehouse_name aimW, w2.warehouse_name fromW " +
                        "FROM t_scm_allocation_order p LEFT JOIN t_bc_user tbu ON p.applicant = tbu.id " +
                        "left join t_bc_organ o on p.company_id = o.id " +
                        "left join t_scm_warehouse w1 on p.aim_warehouse = w1.id " +
                        "left join t_scm_warehouse w2 on p.from_warehouse = w2.id " +
                        "WHERE p.company_id = ? and current_approval_status<>'结束' and current_approval_status in " +
                        "(SELECT circulation_status from t_scm_approvalflow where audit_roles in " +
                        "(SELECT r_id from t_bc_role_user where u_id = ? )) ORDER BY p.create_time desc" +
                        " ) c group by c.company_id limit 1");
                params.add(cid);
                params.add(uid);
                Map map = this.itScmPushMsgDao.info(sql.toString(),params.toArray());
                int allocationCar = Integer.parseInt(map.get("value").toString());
                if(allocationCar>0){
                    Map mm = new HashMap();
                    mm.put("title","待审批的调拨："+allocationCar+"条");
                    mm.put("content","请点击本条消息查看详情!");
                    mm.put("createTime",map.get("createTime"));
                    mm.put("type",1);
                    dataList.add(mm);
                }
            }
            power = m.get("source").toString();
        }
        return dataList;
    }

    /**
     * 判断这个角色是否有权限
     * @param uid
     * @return
     * @throws Exception
     */
    private List confirmRole(String uid) throws Exception{

        List list = this.itScmPushMsgDao.list("select source from t_scm_app_role where r_id in " +
                "(select r_id from t_bc_role_user where u_id=?)",uid);
         return list;
    }

    /**
     * 短信发送
     * @throws Exception
     */
    @Override
    public void sendMessage() throws Exception{
        //给仓库员
        this.sendStocker();
        //给销售经理，给财务经理
        this.sendSalesAndFinancer();
    }

    private void sendStocker() throws Exception{

        List<Map<String,Object>> dataList = new ArrayList<>();
        String rIdS = "fb017e8c5d60fb82015d6106c6510039";//仓库管理员
        List<Map<String,Object>> list = this.itScmPushMsgDao.list("select t.o_p_id,t.u_name,t.u_mobile,ifnull(o.outs,0) outs,ifnull(i.ins,0) ins from (" +
                " select p.o_p_id,u.id,u.u_mobile,u.u_name from t_bc_organ p" +
                " left join t_bc_user u on u.o_id = p.id left join t_bc_role_user ru on u.id = ru.u_id" +
                " where r_id =? and u.id <> '0' ) t left join (" +
                " select company_id,ifnull(count(1),0) as outs from t_scm_outwarehouse" +
                " where out_status = '0' group by company_id ) o on t.o_p_id = o.company_id" +
                " left join ( select company_id,ifnull(count(1),0) as ins from t_scm_car" +
                " where status = '0' and finance_type ='1' group by company_id ) i on t.o_p_id = i.company_id",rIdS);
        if(list.size()>0){
            for(Map<String,Object> map:list){
                Map mm = new HashMap();
                String content = "待入库车辆:"+map.get("ins")+"辆,待出库车辆:"+map.get("outs")+"辆";
                mm.put("mobile",map.get("uMobile"));
                mm.put("content",content);
                dataList.add(mm);
            }
            iSendMsgService.sendPost(dataList,"10661234");
        }
    }

    private void sendSalesAndFinancer() throws Exception{

        List<Map<String,Object>> dataList = new ArrayList<>();
        String rIdM = "fb017e8c5d124c01015d1298bd130031";//销售经理
        String rIdF = "fb017e8c5d124c01015d1298e9ef0033";//财务经理
        String rIdN = "fb017e8c5d61dda2015d64a1590b004a";//内勤
        String rIdS = "fb017e8c5d60fb82015d610613350035";//财务三级账
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        System.out.println(sdf.format(date));
        List params = new ArrayList();
        String sql = "select t.o_p_id,t.u_name,t.u_mobile," +
                " cast(ifnull(f.fin,0) as decimal(10,0)) fin,cast(ifnull(f.fout,0) as decimal(10,0)) fout," +
                "cast(ifnull(f.fstock,0) as decimal(10,0)) fstock,cast(ifnull(f.cin,0) as decimal(10,0)) cin," +
                " cast(ifnull(f.cout,0) as decimal(10,0)) cout,cast(ifnull(f.cstock,0) as decimal(10,0)) cstock from (" +
                " select p.o_p_id,u.id,u.u_mobile,u.u_name from t_bc_organ p" +
                " left join t_bc_user u on u.o_id = p.id left join t_bc_role_user ru on u.id = ru.u_id" +
                " where r_id in (?,?,?,?) and u.id <> '0' ) t left join (" +
                " select f.company_id, (f.new_finance_in-f.old_finance_in) fin,(f.new_finance_out-f.old_finance_out) fout," +
                " (f.new_finance_stock-f.old_finance_stock) fstock,(f.new_finance_in-f.new_car_in) cin,(f.new_finance_out-f.new_car_out) cout," +
                " (f.new_finance_stock-f.new_car_stock) cstock from t_scm_account_finance f" +
                " where f.query_date = ? GROUP BY f.company_id ) f on t.o_p_id = f.company_id";
        params.add(rIdF);
        params.add(rIdM);
        params.add(rIdN);
        params.add(rIdS);
        params.add(sdf.format(date));
        List<Map<String,Object>> list = this.itScmPushMsgDao.list(sql,params.toArray());
        if(list.size()>0){
            for(Map<String,Object> map:list){
                if(map.get("uMobile").toString().length()!=11){
                    continue;
                }
                Map mm = new HashMap();
                String content = "双系统并行入库差异:"+map.get("fin")+"辆,双系统并行出库差异:"+map.get("fout")+
                        "辆,双系统并行库存差异:"+ map.get("fstock").toString()
                        +"辆; 账实入库差异:"+map.get("cin")+"辆,账实出库差异:"+map.get("cout")+
                        "辆,账实库存差异:"+map.get("cstock")+"辆";
                mm.put("mobile",map.get("uMobile"));
                mm.put("content",content);
                dataList.add(mm);
            }
            iSendMsgService.sendPost(dataList,"10661234");
        }
    }

    /**
     * 定时查看销售单是否有公司，没有就发短信
     * @throws Exception
     */
    @Override
    public void saleInvoiceWarn() throws Exception{

        StringBuffer sql = new StringBuffer();
        List<Map<String,Object>> dataList = new ArrayList<>();

        sql.append("select d.id,d.vin from t_scm_sale_order s left join t_scm_sale_order_detail d" +
                " on s.id = d.sale_order_id where s.company_id is null or s.company_id=''");
        List list = this.itScmPushMsgDao.list(sql.toString());
        StringBuffer content = new StringBuffer();
        Map map = new HashMap();
        if(list.size()>0){
            for(int i=0;i<list.size();i++) {
                Map mm = (Map) list.get(i);
                if(i==0){
                    content.append("车辆vin为"+mm.get("vin"));
                }
                if(i!=0&&i!=list.size()-1){
                    content.append(","+mm.get("vin"));
                }
                if(i==list.size()-1){
                    content.append(",没有公司id");
                    map.put("content", content);
                    map.put("mobile", "15098823383");//王恒腾电话
                }

            }
            dataList.add(map);
            iSendMsgService.sendPost(dataList,"10661234");
        }
    }

    /**
     * 定时查看出库的车辆，是否财务也出库了
     * @throws Exception
     */
    @Override
    public void ifInvoiceInsert() throws Exception{

        StringBuffer sql = new StringBuffer();
        List<Map<String,Object>> dataList = new ArrayList<>();
        sql.append("select count(*) as value from t_scm_outwarehouse where car_id not in (select car_id from t_scm_invoice_price" +
                " where invoices_type in ('5','-5') ) and outType ='1'");
        List list = this.itScmPushMsgDao.list(sql.toString());
        StringBuffer content = new StringBuffer();
        Map map = new HashMap();
        if(list.size()>0){
            Map mm = (Map) list.get(0);
            content.append(mm.get("value").toString()+"辆车没有财务出库");
            map.put("content", content);
            map.put("mobile", "15098823383");//王恒腾电话
            dataList.add(map);
            iSendMsgService.sendPost(dataList,"10661234");
        }
    }
}
